import { Button, DatePicker, Input, Select, Switch } from 'antd';
import dayjs from 'dayjs';
import { v4 as uuidv4 } from 'uuid';

import { get } from '@/api';
import PlusIcon from '@/assets/icons/plus.svg';
import { colors } from '@/config/theme';

import {
    INPUT_MAX_DATA_DEFAULT,
    INPUT_MAX_DATA_KEY,
    INPUT_MAX_DATA_NAME,
    INPUT_MIN_DATA_KEY,
    Parameter,
    VarType
} from './data';

export interface VariablesAddProps {}

export interface VariablesAddRef {
    getData: () => void;
    initData: (parameters: any) => void;
}

export const VariablesAdd = memo(
    forwardRef<VariablesAddRef, VariablesAddProps>((props, ref) => {
        const [paramDatas, setParamDatas] = useState<Parameter[]>([]);
        const [fieldTypeOptions, setFieldTypeOptions] = useState<any>([]);

        // 增加行
        const addRow = () => {
            const newRow: Parameter = {
                initValue: '',
                varLabel: '',
                varName: '',
                varType: undefined,
                id: uuidv4(),
            };
            setParamDatas(prevParamDatas => [...prevParamDatas, newRow]);
        };

        const deleteRow = (index: number) => {
            const newParamDatas = [...paramDatas];
            newParamDatas.splice(index, 1);
            setParamDatas(newParamDatas);
        };

        // 值类型
        const fieldTypeRequest = async () => {
            get('/dict/field-type', {} as never).then((res: any) => {
                if (res) {
                    const newList = res.filter((item: any) => item.dictCode !== VarType.Enum);
                    setFieldTypeOptions(newList);
                }
            });
        };

        const handleChange = (varName: string, key: keyof Parameter, value: any) => {
            setParamDatas(prevParamDatas =>
                prevParamDatas.map(item =>
                    item.varName === varName ? { ...item, [key]: value } : item
                )
            );
        };
        
        const handleTimeChange = (varName: string, key: keyof Parameter, value: any) => {
            const date = new Date(value);
            setParamDatas(prevParamDatas =>
                prevParamDatas.map(item =>
                    item.varName === varName ? { ...item, [key]: date.getTime() } : item
                )
            );
        };

        const initData = (parameters?: any[]) => {
            if (parameters) {
                const newList = parameters.map((item: any) => {
                    if (item.varType === 'DATE' || item.varType === 'DATE_TIME') {
                        // 将毫秒时间戳转换为 Date 对象，如果 initValue 不存在，则设置为 null
                        item.initValue = item.initValue ? new Date(Number(item.initValue)) : null;
                    }
                    return { ...item };
                });
                setParamDatas(newList);
            } else {
                setParamDatas([]);
            }
        };

        useEffect(() => {
            fieldTypeRequest();
        }, []);

        useImperativeHandle(ref, () => ({
            initData: (parameters: any[]) => {
                initData(parameters);
            },
            getData: () => {
                let newList: any = [];
                if (paramDatas) {
                    newList = paramDatas.map((item: any) => {
                        if (item.varType === 'DATE' || item.varType === 'DATE_TIME') {
                            const date = item.initValue ? new Date(item.initValue) : null;
                            item.initValue = date ? date.getTime() : null;
                        }
                        return { ...item };
                    });
                }
                return newList;
            },
        }));

        return (
            <div className="w-full p-8 min-h-100 mt-12" style={{ background: '#f7f8fa' }}>
                <div className="w-full" style={{ overflowY: 'auto', overflowX: 'hidden' }}>
                    {
                        paramDatas.map((item: any, index: number) => {
                            // varName不可重复
                            return (
                                <div
                                    key={item.varName}
                                    className="grid gap-x-2 gap-y-6 mt-4 grid-cols-6 pb-8 px-4"
                                    style={{ gridTemplateColumns: 'repeat(4, 1fr) 60px', paddingBottom: '10px' } as React.CSSProperties}
                                >
                                    <div className="flex items-center">
                                        <Input value={item.varLabel} placeholder="请输入中文名称" maxLength={INPUT_MAX_DATA_NAME} className="w-full" onChange={(e) => handleChange(item.varName, 'varLabel', e.target.value)} />
                                    </div>
                                    <div className="flex items-center px-8">
                                        <Input
                                            value={item.varName}
                                            placeholder="请输入英文名称"
                                            min={INPUT_MIN_DATA_KEY}
                                            maxLength={INPUT_MAX_DATA_KEY}
                                            className="w-full"
                                            onChange={(e) => handleChange(item.varName, 'varName', e.target.value)}
                                        />
                                    </div>
                                    <div className="flex items-center px-8">
                                        <Select
                                            value={item.varType}
                                            placeholder="请选择数据类型"
                                            className="w-full"
                                            onChange={(val) => { handleChange(item.varName, 'varType', val); handleChange(item.varName, 'initValue', ''); }}
                                        >
                                            {
                                                fieldTypeOptions.map((option: any) => {
                                                    return (
                                                        <Select.Option key={option.dictCode} value={option.dictCode}>{option.dictName}</Select.Option>
                                                    );
                                                })
                                            }

                                        </Select>
                                    </div>
                                    <div className="flex items-center px-8">
                                        {
                                            item.varType === VarType.Boolean ? <Switch value={item.initValue} onChange={(checked: Boolean) => handleChange(item.varName, 'initValue', checked)} /> :
                                                item.varType === VarType.Date || item.varType === VarType.DateTime ? (
                                                    <DatePicker
                                                        value={item.initValue && dayjs(item.initValue).isValid() ? dayjs(item.initValue) : null}
                                                        showTime={item.varType !== VarType.Date}
                                                        format={item.varType === VarType.Date ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'}
                                                        placeholder={item.varType === VarType.Date ? '请选择日期' : '请选择时间'}
                                                        value-format="x"
                                                        className="w-full"
                                                        style={{ maxWidth: '180px' }}
                                                        onChange={(val) => handleTimeChange(item.varName, 'initValue', val)}
                                                    />
                                                ) : (
                                                    <Input
                                                        value={item.initValue}
                                                        placeholder="请输入默认值"
                                                        maxLength={INPUT_MAX_DATA_DEFAULT}
                                                        className="w-full"
                                                        type={item.varType === VarType.Integer || item.varType === VarType.Decimal ? 'number' : 'text'}
                                                        onChange={(e) => handleChange(item.varName, 'initValue', e.target.value)}
                                                    />
                                                )
                                        }
                                    </div>
                                    <div className="flex items-center px-8">
                                        <Button danger type="link" onClick={() => deleteRow(index)}> 删除 </Button>
                                    </div>
                                </div>
                            );
                        })
                    }

                    <div className="py-4">
                        <Button icon={<PlusIcon className="w-14 h-14" fill={colors.primary[500]} />} type="link" onClick={addRow}> 添加参数 </Button>
                    </div>
                </div>
            </div>
        );
    })
);
